package ru.incoremedia.gwttest.core.server.service;

import com.google.gwt.rpcforms.server.controller.ProcessSubmitController;
import com.google.gwt.rpcforms.server.service.FormServiceImpl;
import java.io.Serializable;
import javax.validation.MessageInterpolator;
import javax.validation.Validator;
import ru.incoremedia.gwttest.core.client.security.UserRole;
import ru.incoremedia.gwttest.core.server.context.RequestContext;
import ru.incoremedia.gwttest.core.server.i18n.MyMessageInterpolator;
import ru.incoremedia.gwttest.core.server.security.Allow;


public class SecuredFormServiceImpl extends FormServiceImpl {

    @Override
    protected Validator getValidator() {
        MessageInterpolator interpolator = new MyMessageInterpolator(getValidatorFactory().getMessageInterpolator(),
                                                                     RequestContext.getInstance().getUserLocale());

        return getValidatorFactory().usingContext().messageInterpolator(interpolator).getValidator();
    }

    @Override
    protected ProcessSubmitController<Serializable> createController(String controllerName) throws Exception {
        ProcessSubmitController<Serializable> controller = super.createController(controllerName);
        
        if(controller.getClass().isAnnotationPresent(Allow.class)) {

            Allow allowAnnotation = controller.getClass().getAnnotation(Allow.class);

            if(!include(RequestContext.getInstance().getUserRole(), allowAnnotation.userRoles())) {
               throw new ru.incoremedia.gwttest.core.client.exception.SecurityException("Access denied");
            }
        }

        return controller;
    }

    private boolean include(UserRole userRole, UserRole[] roles) {
        for(UserRole role : roles) {
            if(userRole.equals(role)) {
                return true;
            }
        }

        return false;
    }

}
